import 'package:chop/Model/DistanceEntity.dart';
import 'package:chop/Model/address_entity.dart';
import 'package:chop/Model/order_entity.dart';
import 'package:chop/Model/priceEntity.dart';
import 'package:chop/common/DateUtils.dart';
import 'package:chop/common/DioUtils.dart';
import 'package:chop/common/SPUtils.dart';
import 'package:chop/common/StringUtils.dart';
import 'package:chop/view/map/New_location.dart';
import 'package:chop/view/pay/pay_list.dart';
//import 'package:chop/view/pay/pay_list.dart';
import 'package:chop/view/sendyou/buy_address.dart';
import 'package:chop/view/sendyou/send_address_page.dart';
import 'package:chop/widgets/TextSizeWidget.dart';
import 'package:chop/widgets/ToastWidget.dart';
import 'package:chop/widgets/appBar.dart';
import 'package:chop/widgets/loadingDialog.dart';
import 'package:chop/widgets/orderWidget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:loading_animations/loading_animations.dart';

class Buy_order extends StatefulWidget {
  final String commodity;

  const Buy_order({Key key, this.commodity}) : super(key: key);

  @override
  _Buy_orderState createState() => _Buy_orderState();
}

class _Buy_orderState extends State<Buy_order> {
  AdrEntityData begin = AdrEntityData(); //起始地址
  AdrEntityData end = AdrEntityData(); //结束地址
  String commodity;
  String range;
  bool isNetWorkBad = false;
  double price;
  String rader = "0";

  TextEditingController _remarks; //备注
  TextEditingController _address; //地址
  TextEditingController _commodity; //购买的商品
  TextEditingController _Suggested_address; //建议地址
  TextEditingController _Estimated_price; //预估商品价格
  TextEditingController _Remarks; //给购买骑手的备注
  TextEditingController _Specific_floor_number; //具体门牌号
  TextEditingController _telephone_number; //发货人电话
  TextEditingController _Specific_name; //发货人姓名

  String longTime;
  DateTime n = DateTime.now();
  @override
  void initState() {
    this.commodity = widget.commodity;
    // TODO: implement initState
    super.initState();
    _address = TextEditingController();
    _Suggested_address = TextEditingController();
    _Estimated_price = TextEditingController();
    _Remarks = TextEditingController();
    _Specific_floor_number = TextEditingController();
    _telephone_number = TextEditingController();
    _Specific_name = TextEditingController();
    _remarks = TextEditingController();
    _commodity = TextEditingController(text: commodity);
    _getDistance();
  }

  int choose;

  //获取距离
  void _getDistance() {
    if(StringUtils.isNull(begin.lat) || StringUtils.isNull(begin.lng)){
      DioUtils.getPrice("0").then((priceEntity price_entity) {
        setState(() {
          isNetWorkBad = true;
          price = price_entity.price;
        });
      });
    }else{
      DioUtils.getTime(
          Position(
              longitude: double.parse(begin.lng),
              latitude: double.parse(begin.lat)),
          Position(
              latitude: double.parse(end.lat),
              longitude: double.parse(end.lng)))
          .then((Map m) {
        if (m['code'] == 500) {
          Toast.toast(context,
              msg: "连接服务器失败",
              bgColor: Colors.redAccent,
              position: ToastPostion.bottom);
          setState(() {
            isNetWorkBad = true;
          });
        } else {
          DistanceEntity distanceEntity = DistanceEntity.fromJson(m);
          range = distanceEntity.rows[0].elements[0].distance.text.substring(
              0, distanceEntity.rows[0].elements[0].distance.text.length - 3);
          longTime = DateUtils.getMins(
              distanceEntity.rows[0].elements[0].duration.text);
          var now = DateTime.now();
          n = now.add(Duration(minutes: int.parse(longTime) + 20));
          print("需要的时间：——————————————————————》${n}");
          DioUtils.getPrice(range).then((priceEntity price_entity) {
            setState(() {
              isNetWorkBad = true;
              price = price_entity.price;
            });
          });
        }
      });
    }

  }
  String splitAddress(String str){
    List<String> arr = str.split(",");
    return "${arr[0]} ${arr[1]}";
  }
  Widget getBody() {
    if (isNetWorkBad) {
      if(price == null){
        return Center(child: FixedSizeText("连接服务器失败"),);
      }else{
        return ListView(
          children: <Widget>[
            // 地址信息
            getColumn(
              "地址信息",
              child: Column(
                children: <Widget>[
                  getAddress(begin,
                      iconText: "买",
                      iconBgColor: Colors.blue,
                      iconTextStyle: TextStyle(
                        color: Colors.white,
                      ), callback: () async {
                        var result = await Get.to(NewLocation());
                        if(result != null){
                          if(StringUtils.isNotNull(end.address)){
                            begin = result;
                            begin.address = splitAddress(begin.address);
                            _getDistance();
                            Get.back();
                          }else{
                            setState(() {
                              begin = result;
                              begin.address = splitAddress(begin.address);
                              begin.remark = begin.address;
                            });
                            print(begin.toJson());
                          }
                        }
                      }),
                  Container(
                    height: 10,
                  ),
                  getAddress(end,
                      iconText: "收",
                      iconBgColor: Colors.green,
                      iconTextStyle: TextStyle(
                        color: Colors.white,
                      ), callback: () async {
                        var result = await Get.to(sendAddressPage(isSend: true,));
                        if(result != null){
                          print(result);
                          if(StringUtils.isNotNull(begin.address)){
                            end = result;
                            _getDistance();
                          }else{
                            setState(() {
                              end = result;
                            });
                          }
                        }
                      }),
                ],
              ),
            ),
            getColumn(
              "商品信息",
              child: Column(
                children: <Widget>[
                  Container(
                    child: TextField(
                      controller: _commodity,
                      maxLines: 4,
                      decoration: InputDecoration(border: InputBorder.none),
                    ),
                  )
                ],
              ),
            ),
            getColumn(
              "帮我送",
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          child: FixedSizeText(
                            "路程",
                            style: TextStyle(color: Colors.black45),
                          ),
                        ),
                      ),
                      Expanded(
                        child: Container(
                          alignment: Alignment.topRight,
                          child: FixedSizeText("${range??'0'} km   "),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          child: FixedSizeText(
                            "跑腿费",
                            style: TextStyle(color: Colors.black45),
                          ),
                        ),
                      ),
                      Expanded(
                        child: Container(
                          alignment: Alignment.topRight,
                          child: FixedSizeText("${price} \$   "),
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
            getColumn(
              "描述物品及备注",
              child: Column(
                children: <Widget>[
                  Container(
                    child: TextField(
                      controller: _remarks,
                      maxLines: 4,
                      decoration: InputDecoration(border: InputBorder.none),
                    ),
                  )
                ],
              ),
            ),
          ],
        );
      }

    } else {
      return Center(child: LoadingJumpingLine.square());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: BaseViewBar(
          childView: BaseTitleBar(
            "提交订单",
            leftIcon: Icons.clear,
          ),
          preferredSize: Size.fromHeight(50.0),
        ),
        body: Stack(
          children: <Widget>[
            getBody(),
            Positioned(
              bottom: 0,
              width: MediaQuery.of(context).size.width,
              child: Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(17)),
                    boxShadow: [
                      BoxShadow(
                        color: Color(000000),
                        blurRadius: 5.0,
                      ),
                    ],
                    color: Colors.white),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 7,
                      child: Row(
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(left: 10),
                            child: FixedSizeText(
                              "${price ?? ''} \$",
                              style: TextStyle(
                                  fontSize: 24,
                                  color: Colors.orange,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                          GestureDetector(
                            child: FixedSizeText(
                              "  费用详细 >",
                              style: TextStyle(
                                  fontSize: 12, fontWeight: FontWeight.bold),
                            ),
                          )
                        ],
                      ),
                    ),
                    Expanded(
                        flex: 3,
                        child: Center(
                          child: RaisedButton(
                            //提交按钮
                            color: Colors.lightBlueAccent,
                            highlightColor: Colors.blueAccent,
                            splashColor: Colors.blue,
                            colorBrightness: Brightness.dark,
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10)),
                            onPressed: () async {
                              if(StringUtils.isNull(begin.address)){
                                Toast.toast(context,msg: "请选择商品购买地址",bgColor: Colors.redAccent);
                              }else if(StringUtils.isNull(end.address)){
                                Toast.toast(context,msg: "请选择送达地址",bgColor: Colors.redAccent);
                              }else {
                                showDialog<Null>(
                                  context: context, //BuildContext对象
                                  barrierDismissible: false,
                                  builder: (BuildContext context) {
                                    return LoadingDialog(
                                      //调用对话框
                                      text: '请稍后...',
                                    );
                                  },
                                );
                                orderData data = orderData();
                                data.begin = "${begin.address} ${begin.remark}";
                                data.end = "${end.address} ${end.remark}";
                                data.endName = end.name;
                                data.distance = double.parse(range);
                                data.money = price;
                                data.beginLat = begin.lat;
                                data.beginLng = begin.lng;
                                data.endLng = end.lng;
                                data.endLat = end.lat;
                                data.fromId = int.parse(await SPUtils.get("UID"));
                                data.fromName = begin.name;
                                data.commodity = _commodity.text.trim();
                                data.orderType = "2";
                                data.status = "2";
                                data.estimatedTime = n.toString().substring(0,19);
                                data.remark = _remarks.text.trim();
                                await DioUtils.orderAdd(data)
                                    .then((OrderEntity orderEntity) {
                                  Get.back();
                                  if (orderEntity.code == 500) {
                                    Toast.toast(context,
                                        msg: "请稍后重试", bgColor: Colors.redAccent);
                                    print("发起订单发生错误： ${orderEntity.msg}");
                                  } else if (orderEntity.code == 0) {
                                    Get.to(PayList(
                                      orderdata: orderEntity.data,
                                    ));
                                  } else {
                                    Toast.toast(context,
                                        msg: "发生未知原因错误",
                                        bgColor: Colors.redAccent);
                                  }
                                });
                              }

//                              Get.to(PayList());
                            },
                            child: FixedSizeText(
                              '下单',
                              style:
                              TextStyle(color: Colors.white, fontSize: 15),
                            ),
                          ),
                        ))
                  ],
                ),
              ),
            ),
          ],
        ));
  }
}

Widget getColumn(String title, {Widget child}) {
  return Container(
    margin: EdgeInsets.only(top: 10, right: 10, left: 10),
    padding: EdgeInsets.fromLTRB(20.0, 15.0, 10.0, 20.0),
    decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(17),
        border: Border.all(color: Colors.white, width: 1),
        color: Colors.white),
    child: Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(bottom: 5),
          padding: EdgeInsets.only(bottom: 5),
          width: double.infinity,
          decoration: BoxDecoration(
              border:
              Border(bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))
//                  border: Border(bottom:BorderSide(width: 1,color: Color(0xffe5e5e5))
          ),
          child: FixedSizeText(
            title,
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          alignment: Alignment.topLeft,
        ),
        child
      ],
    ),
  );
}
